package com.jlboot.app.admin.interceptor;
import cn.dev33.satoken.exception.*;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jlboot.core.Results;
import com.jlboot.core.consts.CoreResponseCode;
import com.jlboot.core.exception.JlLogicException;
import com.jlboot.core.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 51594 on 2022/7/27.
 */
@Slf4j
public class AdminGlobalInterceptor implements Interceptor {


    @Override
    public void intercept(Invocation inv) {


        Integer code=null;
        String msg=null;
        boolean invokeSuccess=true;
        try {
            inv.invoke();
        }catch (Exception e){
            invokeSuccess=false;

            if(e instanceof NotLoginException){
                code=CoreResponseCode.UN_LOGIN.getCode();
                msg=CoreResponseCode.UN_LOGIN.getName();
            }else if(e instanceof NotPermissionException){
                code=CoreResponseCode.NO_PERMISSION.getCode();
                msg=CoreResponseCode.NO_PERMISSION.getName();
            }else if(e instanceof NotRoleException){
                code=CoreResponseCode.NO_PERMISSION.getCode();
                msg=CoreResponseCode.NO_PERMISSION.getName();
            }else if(e instanceof NotBasicAuthException){
                code=CoreResponseCode.NO_PERMISSION.getCode();
                msg=CoreResponseCode.NO_PERMISSION.getName();
            }else if(e instanceof SaTokenException){
                code=CoreResponseCode.NO_PERMISSION.getCode();
                msg=CoreResponseCode.NO_PERMISSION.getName();
            }else if(e instanceof JlLogicException){
                JlLogicException jle=(JlLogicException) e;
                code=jle.getCode();
                msg=jle.getMsg();
            }else{

                log.error("系统异常.Exception",e);

                code=CoreResponseCode.SERVER_ERROR.getCode();
                msg=CoreResponseCode.SERVER_ERROR.getName();
            }
        }

        //如果失败
        if(!invokeSuccess){
            HttpServletRequest request=inv.getController().getRequest();
            boolean isAjax= HttpUtil.isAjax(request);

            if(isAjax){
                inv.getController().renderJson(Results.n(code, msg));
            }else{

                if(CoreResponseCode.UN_LOGIN.getCode().equals(code)){
                    inv.getController().render("/WEB-INF/resource/pages/admin/error/no_login.html");
                }else if(CoreResponseCode.NO_PERMISSION.getCode().equals(code)){
                    inv.getController().render("/WEB-INF/resource/pages/admin/error/no_permission.html.html");
                }else{
                    inv.getController().render("/WEB-INF/resource/pages/admin/error/500.html");
                }


            }
        }
    }
}
